<template>
  <div class="tree-node">
    <!-- 节点内容区域 -->
    <div class="node-content" @click="toggleExpand">
      <!-- 展开/折叠图标 -->
      <span class="toggle-icon" v-if="hasChildren">
        {{ isExpanded ? '▼' : '▶' }}
      </span>
      <!-- 节点文本 -->
      <span class="node-label">{{ node.label }}</span>
    </div>

    <!-- 递归渲染子节点 -->
    <div class="children-container" v-if="isExpanded && hasChildren">
      <TreeNode v-for="child in node.children" :key="child.id" :node="child" />
    </div>
  </div>
</template>

<script setup>
  import { ref, computed } from 'vue'

  // 接收父组件传递过来的当前节点数据
  const props = defineProps({
    node: {
      type: Object,
      required: true
    }
  })

  // 状态：记录当前节点是否展开
  const isExpanded = ref(false)

  // 计算属性：判断当前节点是否有子节点
  const hasChildren = computed(() => {
    return props.node.children && props.node.children.length > 0
  })

  // 方法：切换节点的展开/折叠状态
  const toggleExpand = () => {
    // 只有当有子节点时，才可以展开/折叠
    if (hasChildren.value) {
      isExpanded.value = !isExpanded.value
    }
  }
</script>

<style scoped>
  .tree-node {
    margin-left: 8px;
  }

  .node-content {
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 4px 0;
    font-size: 14px;
  }

  .toggle-icon {
    margin-right: 4px;
    font-size: 12px;
    color: #666;
  }

  /* 子节点容器，通过缩进体现层级关系 */
  .children-container {
    margin-left: 16px;
    border-left: 1px dashed #ddd;
    padding-left: 8px;
  }
</style>
